package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.item.dto.SpecGroupDTO;
import com.leyou.item.dto.SpecParamDTO;
import com.leyou.item.entity.SpecGroup;
import com.leyou.item.mapper.SpecGroupMapper;
import com.leyou.item.service.SpecGroupService;
import com.leyou.item.service.SpecParamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class SpecGroupServiceImpl extends ServiceImpl<SpecGroupMapper, SpecGroup> implements SpecGroupService {

   @Autowired
   private SpecParamService specParamService;
    //根据商品分类id，查询规格组的集合
    @Override
    public List<SpecGroupDTO> querycategoryById(Long cid) {
        //select id from group where category_id =#{id}
        List<SpecGroupDTO> groupids = query()
                .eq("category_id", cid)
                .list()
                .stream()
                .map(SpecGroupDTO::new)
                .collect(Collectors.toList());
        return groupids;
    }

    //先获取group的id然后在求param
    @Override
    public List<SpecGroupDTO> querygrouporparam(Long ids) {

        List<SpecGroupDTO> groupids = SpecGroupDTO.convertEntityList(query().eq("category_id", ids).list());
        // 查询规格参数
        List<SpecParamDTO> paramList = specParamService.querySpecParams(ids, null, null);
        // 对规格参数分组，groupId一致的在一组
        Map<Long, List<SpecParamDTO>> map = paramList.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));
        // 把参数放入group
        for (SpecGroupDTO groupDTO : groupids) {
            groupDTO.setParams(map.get(groupDTO.getId()));
        }
        return  groupids;
    }

    @Override
    public void addgroup(SpecGroupDTO specGroupDTO) {
        SpecGroup group = specGroupDTO.toEntity(SpecGroup.class);
        this.save(group);

    }

    @Override
    public void updategroup(SpecGroupDTO specGroupDTO) {
        SpecGroup group = specGroupDTO.toEntity(SpecGroup.class);
        this.updateById(group);
    }


    @Override
    public List<SpecGroupDTO> querySpecList(long cid) {
        List<SpecGroupDTO> groupDTOS = this.querycategoryById(cid);
        //根据分类id查询对应的规格参数
        List<SpecParamDTO> specParamDTOS = SpecParamDTO.convertEntityList(this.specParamService.query().eq("category_id", cid).list());
        //对查询的规格参数进行分组操作，key为参数组的id，value为参数组的组内集合
        Map<Long, List<SpecParamDTO>> paramDTOmap = specParamDTOS.stream().collect(Collectors.groupingBy(SpecParamDTO::getGroupId));

        groupDTOS.forEach(specGroupDTO -> {
            specGroupDTO.setParams(paramDTOmap.get(specGroupDTO.getId()));
        }) ;
        return groupDTOS;
    }


}